import {Component, OnDestroy, OnInit} from '@angular/core';
import {TableUtil} from '../../../util/table-util';
import {MsgConstants} from '../../../constants/constants';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {MsgResult} from '../../../models/msg-result';
import {PageSubject} from '../../../util/page-subject';
import {Observable} from 'rxjs/Observable';
import {ActivatedRoute, Router} from '@angular/router';
import {ResponseUtil} from '../../../util/response-util';
import {DaAPI, DaChartColor, DaChartTitle, DaFactorColor, DaFactorName} from '../da-constants';
import {DaInodataService} from './da-inodata.service';

declare var $;
declare var moment;
declare var echarts;

@Component({
  selector: 'app-da-inodata',
  templateUrl: './da-inodata.component.html',
  styleUrls: ['./da-inodata.component.css']
})
export class DaInodataComponent implements OnInit, OnDestroy {
  config;
  pointType = 'skyEyeSite'; // 点位类型
  factor = 'PM2_5';
  timeDataType = 'hourData';
  siteCode = '';
  rangeCode = '';
  siteArr: Array<any> = [];
  nationCode = '';
  chartObj: any;
  chartOption: object;
  isLoading = true;
  resizeEnent: any;
  timeDataArr: Array<any> = [];
  table: any;
  startDate = new Date(moment().subtract(1, 'w').format('YYYY/MM/DD HH:00'));
  endDate =  new Date();
  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private dialogService: OneDialogService,
    private response: ResponseUtil,
    private tableUtil: TableUtil,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private inodataService: DaInodataService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.screenChange();
    this.initData();
    this.getSiteData();
  }
  ngOnDestroy () {
    this.destroyResize();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    const path = new Path(' 无机元素分析', '');
    this.pageSubject.pushPage('数据曲线', '查询', path);
  }

  initData = () => {
    $('#inodataChart').css({'height': $(window.innerHeight)[0] - 230 + 'px'});
    $('#typePie').css({ 'height': $(window.innerHeight)[0] - 230 + 'px'});
    this.timeDataArr = [{name: '小时', dataType: 'hourData'}, { name: '日', dataType: 'dayData'}, {name: '周', dataType: 'weekData'}];
    this.chartObj = echarts.init(document.getElementById('inodataChart'));
    // this.typePieObj = echarts.init(document.getElementById('typePie'));
    const chartList = {
      'siteName': '河南省站',
      'nameList': [
        'K',
        'Cl',
        'Ar',
        'Si',
        'S',
        'P',
        'Ca',
        'Sc',
        'Ti',
        'V',
        'Cr',
        'Mn',
        'Fe',
        'Ni',
        'Cu',
        'Zn',
        'Ga',
        'As',
        'Se',
        'Br',
        'Sr',
        'Mo',
        'Pd',
        'Ag',
        'Cd',
        'Sn',
        'Sb',
        'Te',
        'Cs',
        'Ba',
        'Hg',
        'Tl',
        'Pb',
        'Al',
        'PM2.5'
      ],
      'timeList': [
        '2018-04-21 10:00',
        '2018-04-21 14:00',
        '2018-04-21 18:00',
        '2018-04-21 22:00',
        '2018-04-22 02:00',
        '2018-04-22 06:00',
        '2018-04-22 10:00',
        '2018-04-22 14:00',
        '2018-04-22 18:00',
        '2018-04-22 22:00',
        '2018-04-23 02:00',
        '2018-04-23 06:00',
        '2018-04-23 10:00',
        '2018-04-23 14:00',
        '2018-04-23 18:00',
        '2018-04-23 22:00',
        '2018-04-24 02:00',
        '2018-04-24 06:00',
        '2018-04-24 10:00',
        '2018-04-24 14:00'
      ],
      'dataList': [
        [
          55,
          80,
          8,
          97,
          73,
          49,
          93,
          25,
          69,
          53,
          86,
          96,
          34,
          19,
          2,
          31,
          51,
          64,
          21,
          28
        ],
        [
          68,
          19,
          76,
          68,
          44,
          36,
          23,
          43,
          14,
          96,
          0,
          8,
          77,
          12,
          90,
          81,
          27,
          47,
          53,
          22
        ],
        [
          92,
          15,
          7,
          82,
          13,
          92,
          80,
          13,
          36,
          59,
          66,
          73,
          66,
          37,
          17,
          58,
          67,
          75,
          69,
          40
        ],
        [
          84,
          70,
          17,
          59,
          85,
          31,
          12,
          62,
          9,
          6,
          5,
          39,
          24,
          65,
          76,
          97,
          93,
          44,
          4,
          2
        ],
        [
          16,
          7,
          10,
          72,
          68,
          13,
          40,
          84,
          84,
          14,
          75,
          1,
          27,
          3,
          36,
          9,
          88,
          78,
          36,
          25
        ],
        [
          0,
          1,
          43,
          89,
          37,
          34,
          53,
          49,
          49,
          83,
          96,
          73,
          0,
          62,
          54,
          91,
          27,
          15,
          65,
          71
        ],
        [
          8,
          43,
          32,
          31,
          60,
          76,
          87,
          41,
          56,
          21,
          81,
          26,
          38,
          72,
          15,
          56,
          78,
          2,
          95,
          88
        ],
        [
          99,
          64,
          76,
          16,
          29,
          85,
          55,
          19,
          3,
          39,
          24,
          17,
          81,
          15,
          86,
          34,
          44,
          47,
          59,
          4
        ],
        [
          26,
          77,
          47,
          84,
          56,
          54,
          57,
          42,
          71,
          77,
          29,
          20,
          40,
          61,
          47,
          21,
          43,
          85,
          5,
          13
        ],
        [
          28,
          65,
          60,
          46,
          87,
          31,
          47,
          64,
          85,
          40,
          4,
          26,
          19,
          23,
          86,
          85,
          8,
          49,
          29,
          82
        ],
        [
          58,
          5,
          33,
          92,
          64,
          47,
          23,
          73,
          18,
          56,
          97,
          37,
          32,
          55,
          95,
          86,
          57,
          60,
          18,
          17
        ],
        [
          87,
          29,
          51,
          25,
          13,
          45,
          33,
          66,
          46,
          78,
          78,
          91,
          79,
          32,
          1,
          14,
          88,
          98,
          59,
          35
        ],
        [
          21,
          100,
          13,
          53,
          62,
          66,
          86,
          100,
          5,
          80,
          31,
          0,
          7,
          24,
          72,
          34,
          82,
          12,
          15,
          44
        ],
        [
          30,
          32,
          7,
          94,
          50,
          57,
          41,
          86,
          57,
          50,
          92,
          77,
          44,
          78,
          8,
          49,
          96,
          74,
          34,
          45
        ],
        [
          22,
          81,
          87,
          80,
          86,
          23,
          16,
          87,
          41,
          23,
          39,
          70,
          90,
          8,
          9,
          80,
          16,
          98,
          60,
          43
        ],
        [
          68,
          59,
          76,
          24,
          69,
          15,
          8,
          12,
          63,
          60,
          42,
          6,
          32,
          95,
          75,
          38,
          85,
          79,
          25,
          32
        ],
        [
          52,
          57,
          39,
          3,
          32,
          88,
          43,
          13,
          69,
          7,
          37,
          70,
          38,
          10,
          96,
          1,
          60,
          91,
          81,
          8
        ],
        [
          16,
          26,
          44,
          23,
          36,
          68,
          3,
          42,
          34,
          42,
          30,
          12,
          52,
          45,
          3,
          71,
          63,
          38,
          35,
          23
        ],
        [
          28,
          50,
          100,
          19,
          28,
          34,
          5,
          6,
          41,
          33,
          18,
          48,
          72,
          36,
          4,
          40,
          58,
          65,
          73,
          3
        ],
        [
          27,
          46,
          36,
          95,
          40,
          81,
          53,
          86,
          53,
          33,
          77,
          60,
          59,
          57,
          40,
          81,
          36,
          44,
          2,
          48
        ],
        [
          95,
          19,
          26,
          59,
          32,
          49,
          46,
          98,
          20,
          2,
          28,
          0,
          95,
          25,
          71,
          99,
          7,
          98,
          29,
          53
        ],
        [
          78,
          92,
          80,
          47,
          52,
          40,
          22,
          7,
          97,
          36,
          77,
          35,
          99,
          94,
          55,
          26,
          25,
          14,
          100,
          76
        ],
        [
          50,
          29,
          97,
          46,
          94,
          98,
          53,
          8,
          27,
          93,
          7,
          100,
          42,
          23,
          35,
          2,
          83,
          28,
          49,
          58
        ],
        [
          89,
          92,
          78,
          82,
          39,
          29,
          10,
          39,
          46,
          80,
          98,
          13,
          41,
          98,
          15,
          74,
          96,
          1,
          5,
          18
        ],
        [
          3,
          28,
          95,
          27,
          62,
          72,
          30,
          7,
          77,
          62,
          28,
          59,
          64,
          42,
          71,
          8,
          11,
          0,
          21,
          45
        ],
        [
          7,
          64,
          58,
          55,
          44,
          36,
          95,
          1,
          4,
          77,
          90,
          0,
          86,
          15,
          8,
          97,
          3,
          62,
          97,
          98
        ],
        [
          82,
          41,
          28,
          92,
          33,
          69,
          73,
          39,
          40,
          36,
          19,
          28,
          30,
          34,
          13,
          86,
          98,
          83,
          57,
          3
        ],
        [
          74,
          49,
          70,
          16,
          39,
          44,
          87,
          62,
          16,
          100,
          58,
          28,
          17,
          99,
          20,
          3,
          0,
          70,
          39,
          10
        ],
        [
          80,
          32,
          31,
          98,
          86,
          4,
          92,
          94,
          3,
          29,
          45,
          41,
          9,
          26,
          22,
          4,
          61,
          82,
          85,
          2
        ],
        [
          29,
          91,
          13,
          77,
          22,
          9,
          33,
          2,
          73,
          80,
          19,
          27,
          64,
          19,
          23,
          90,
          50,
          42,
          43,
          47
        ],
        [
          95,
          86,
          86,
          68,
          78,
          66,
          66,
          74,
          48,
          30,
          19,
          79,
          20,
          23,
          10,
          29,
          41,
          21,
          73,
          4
        ],
        [
          70,
          42,
          49,
          15,
          58,
          55,
          98,
          73,
          47,
          63,
          68,
          81,
          8,
          14,
          2,
          100,
          55,
          71,
          45,
          80
        ],
        [
          43,
          80,
          51,
          90,
          56,
          2,
          27,
          99,
          14,
          87,
          52,
          46,
          93,
          83,
          0,
          78,
          57,
          16,
          52,
          36
        ],
        [
          93,
          11,
          0,
          5,
          11,
          30,
          24,
          34,
          67,
          58,
          48,
          24,
          51,
          99,
          91,
          13,
          4,
          55,
          26,
          98
        ],
        [
          61,
          68,
          54,
          81,
          49,
          11,
          10,
          54,
          21,
          52,
          12,
          10,
          9,
          54,
          37,
          50,
          79,
          94,
          47,
          10
        ]
      ]
    };
    // this.chartRender(chartList);
  };
  /**
   * 屏幕大小改变
   */
  screenChange() {
    this.resizeEnent = Observable.fromEvent(window, 'resize')
      .debounceTime(100) // 以免频繁处理
      .subscribe((event) => {
        // 这里处理页面变化时的操作
        this.chartObj.resize();
      });
  }
  /**
   * 取消监听屏幕变化
   * */
  destroyResize() {
    this.resizeEnent.unsubscribe();
  }
  search() {
    if (this.startDate > this.endDate) {
      this.dialogService.info('开始时间大于结束时间，请重新选择');
    } else {
      this.isLoading = true;
      this.getInodata();
    }
  }

  /**
   * 图表
   * @param chartList
   */
  chartRender(chartList) {
    const compareChart = this.chartObj;
    const select = {};
    const nameArr = [];
    if (chartList.nameList && chartList.nameList.length > 0) {
      chartList.nameList.forEach((val, i) => {
        const name = DaFactorName[val] || val;
        nameArr.push(name);
        if (i < 14) {
          select[name] = true;
        } else {
          select[name] = false;
        }
        if (val === 'PM₂.₅') {
          select[name] = true;
        }
      })
    }
    // 图表配置信息
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: this.formatterChartTooltip
      },
      title: [{
        left: 'center',
        text: DaChartTitle.daInoDataTitle
      }],
      toolbox: {
        right: '30',
        feature: {
          saveAsImage: {}
        }
      },
      dataZoom: [
        // {
        //   type: 'slider',
        //   show: true,
        //   xAxisIndex: [0]
        // },
        {
          type: 'inside',
          xAxisIndex: [0]
        }
      ],
      legend: {
        bottom: 40,
        left: 'center',
        selected: select,
        width: '90%',
        data: nameArr
      },
      grid: [{
        top: 40,
        bottom: 140
      }],
      color: DaChartColor.color,
      xAxis: [
        {
          type: 'category',
          nameGap: '20',
          // name: '日期',
          nameLocation: 'start',
          boundaryGap: false,
          data: chartList.timeList,
          axisLabel: {
            // rotate: 45,
            color: '#000',
            formatter: (value, index) => {
              // 格式化
              const h = moment(value).format('H:00');
              if (this.timeDataType === 'hourData') {
                return moment(value).format('M月D日 ')  + '\n' + h;
              } else if (this.timeDataType === 'dayData')  {
                return moment(value).format('M月D日 ')
              } else if (this.timeDataType === 'weekData')  {
                return moment(value).format('M月D日')
              } else if (this.timeDataType === 'yearData')  {
                return moment(value).format('YYYY年 ')
              }
            }
          }
        }
      ],
      yAxis: [
        {
          name: 'μg/m³',
          type: 'value',
          splitLine: {
            show: false
          }
        }, {
          name: 'μg/m³',
          type: 'value',
          splitLine: {
            show: false
          }
        }
      ],
      series: [

      ]
    };
    const seriesObj = [];
    chartList.nameList.forEach((name, i) => {
      const dataObj = {
        type: 'line',
        smooth: true,
        barMaxWidth: 40,
        name: DaFactorName[name] || name,
        data: chartList.dataList[i],
        itemStyle: {
          color: DaFactorColor[chartList.codeList[i]] || DaChartColor.color[i]
        },
        lineStyle: {
          color: DaFactorColor[chartList.codeList[i]] || DaChartColor.color[i]
        }
      };
      if (name === 'PM₂.₅') {
        Object.assign(dataObj, {yAxisIndex: 1, lineStyle: {color: DaChartColor.PM25Color}, itemStyle: {color: DaChartColor.PM25Color}})
      } else {
        // stack: '总量'
        Object.assign(dataObj, {yAxisIndex: 0})
      }
      seriesObj.push(dataObj)
    });
    option.series = seriesObj;
    this.chartOption = option;
    compareChart.setOption(option, {notMerge: true});
  }
  formatterChartTooltip = (params) => {
    let strRet = '';
    params.forEach((val, i) => {
      let brHtml = '';
      if (i === 0) {
        strRet += '<div>' + params[0].axisValue + '</div>';
      }
      if ((i + 1) % 6 === 0) {
        brHtml = '<br/>';
      }
      strRet += '<div style="display:inline-block;margin-right:6px;">' +
        '<span style="display:inline-block;margin-right:3px;border-radius:10px;width:9px;height:9px;background-color:'
        + params[i].color +
        '";></span>' + val.seriesName + ' : ' + (val.value || ' ') +  '</div>' + brHtml;
    });
    return strRet;
  };
  /**
   * 时间类型切换
   * @param timeDataType
   */
  timeDataChange(timeDataType) {
    if (this.timeDataType === timeDataType) {
      return false;
    }
    this.timeDataType = timeDataType;
    this.changeStartAndEndDate();
    this.search();
  }
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  && startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };
  get showTimeParams() {
    if (this.timeDataType === 'hourData') {
      return {
        nzFormat: 'HH'
      }
    } else {
      return false;
    }
  }
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    this.inodataService.getSiteData().subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        this.siteCode = this.siteArr[0].SITECODE;
        this.rangeCode = this.siteArr[0].RANGECODE;
        this.changeSite(false);
        this.getInodata();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            this.changeStartAndEndDate();
          }
        }
      } else {
        this.disabledDate = [];
      }
    }
  };
  /**
   * 修改开始结束时间
   */
  changeStartAndEndDate = () => {
    if (this.disabledDate.length > 0) {
      const dateLength = this.disabledDate.length;
      const dateObj = this.disabledDate[dateLength - 1];
      const startTime = new Date(moment(dateObj.startDate).format('YYYY/MM/DD 00:00:00'));
      const endTime = new Date(moment(dateObj.endDate).format('YYYY/MM/DD 00:00:00'));
      const nowDate =  new Date(moment().format('YYYY/MM/DD 00:00:00'));
      const nowDateIsInRange = startTime.getTime() < nowDate.getTime()  && nowDate.getTime() <= endTime.getTime();
      if (nowDateIsInRange) {
        this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        let startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          startDate = new Date(moment().subtract('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          startDate = new Date(moment().subtract('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          startDate = new Date(moment().subtract('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        const startDateIsInRange = startTime.getTime() < startDate.getTime()  && startDate.getTime() < endTime.getTime();
        if (startDateIsInRange) {
          this.startDate = startDate;
        } else {
          this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        }
      } else {
        this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        let endDate = new Date(moment(dateObj.endDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        if (endDate.getTime() > new Date().getTime()) {
          this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        } else {
          this.endDate = endDate;
        }
      }
    }
  };
  /**
   * 获取图表数据
   */
  getInodata() {
    const dataObj = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      startTime : this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '',
      endTime : this.endDate ? moment(this.endDate).format('YYYY-MM-DD HH:00:00') : ''
    };
    this.inodataService.getInodata(dataObj).subscribe(
      result => this.response.success(result, this.handleInodata),
      error => this.response.error(error)
    );
  }
  handleInodata = (result: MsgResult) => {
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data) {
        this.chartRender(result.data)
      } else {
        this.chartRender({
          timeList: [],
          nameList: [],
          dataList: []
        });
      }
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

}
